import { Component, OnInit, OnDestroy, ViewChild, TemplateRef } from '@angular/core'
import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { PostRiskScheme } from '@shared/interfaces/post-risk-control'
import { ActivatedRoute, Router } from '@angular/router'
import { PageService } from '@shared/services/page.service'
import { NzMessageService } from 'ng-zorro-antd'
import { IDetailHeaderTab, SchemeStatusTextMap } from '@shared/interfaces/common'
import { PostRiskService } from '../post-risk.service'
import { DataService } from '@shared/services/data.service'
import { deepCopy } from '@delon/util'
import { Validators } from 'app/utils/validator'
import { riskControlSchemeNameLength } from 'app/utils/contraints'
import { I18NService } from '@core'
import { PostRiskStoreService } from '../new/post-risk-store.service'
import { AcquirerService } from '../../acquirer/acquirer.service'
import { take } from 'rxjs/operators'

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styles: [],
})
export class DetailComponent extends DetailBaseClass<PostRiskScheme> implements OnInit, OnDestroy {
  @ViewChild('tplControl') tplControl: TemplateRef<void>
  @ViewChild('tpCurrency') tpCurrency: TemplateRef<any>
  tabs: IDetailHeaderTab[] = [
    { text: this.trans('RISK_CTRL.RULES'), url: './rules' },
    { text: this.trans('GENERAL.INFO.RANGE'), url: './range' },
    { text: this.trans('AUDIT.TYPE.STORE'), url: './merchant' },
  ]

  constructor(
    public route: ActivatedRoute,
    public router: Router,
    public msg: NzMessageService,
    public pageService: PageService,
    private riskService: PostRiskService,
    private dataService: DataService,
    private i18n: I18NService,
    private riskStore: PostRiskStoreService,
    public acquirerService: AcquirerService,
  ) {
    super(pageService)
  }

  ngOnInit() {
    this.loading = true
    this.id = this.route.snapshot.params['id']
    this.request()
  }

  ngOnDestroy() {
    this.dataService.resetCurrentPostrisk()
  }

  request(): void {
    this.riskService.getOne(this.id).subscribe((riskControlScheme: PostRiskScheme) => {
      this.display(riskControlScheme)
      this.dataService.setCurrentPostrisk(riskControlScheme)
      this.loading = false
    })
  }

  display(riskControlScheme: PostRiskScheme): void {
    this.renderRisk(riskControlScheme)
    this.saveDataToDataStore(deepCopy(riskControlScheme))
    this.initialColumns()
    this.initColumns()
  }

  renderRisk(riskScheme: PostRiskScheme): void {
    this.detailData = riskScheme
  }

  saveDataToDataStore(riskScheme: PostRiskScheme): void {
    this.dataService.sePostRiskScheme(riskScheme)
  }

  resetDetailData(): void {
    this.detailData = this.dataService.postRiskScheme
  }

  initialColumns(): void {
    this.firstColumns = [
      {
        span: 6,
        index: 'schemeCode',
        label: 'RISK_CTRL.SCHEME_CODE',
        labelI18n: 'RISK_CTRL.SCHEME_CODE',
        disEditable: true,
      },
      {
        span: 6,
        index: 'schemeName',
        label: 'RISK_CTRL.SCHEME_NAME',
        labelI18n: 'RISK_CTRL.SCHEME_NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(riskControlSchemeNameLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: riskControlSchemeNameLength }),
          ],
        },
      },
      {
        span: 5,
        index: 'insCode',
        label: 'ROLE.OWNER_INSTITUTION',
        labelI18n: 'ROLE.OWNER_INSTITUTION',
        disEditable: true,
      },
      {
        span: 5,
        index: 'currency',
        label: 'GENERAL.INFO.CURRENCY',
        labelI18n: 'GENERAL.INFO.CURRENCY',
        template: this.tpCurrency,
      },
    ]
    this.secondColumns = [
      {
        span: 6,
        index: 'schemeDesc',
        label: 'RISK_CTRL.SCHEME_DESC',
        labelI18n: 'RISK_CTRL.SCHEME_DESC',
      },
      {
        span: 6,
        index: 'createdAt',
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        type: 'date',
        disEditable: true,
      },
      {
        span: 6,
        index: 'updatedAt',
        label: 'GENERAL.INFO.UPDATED_AT',
        labelI18n: 'GENERAL.INFO.UPDATED_AT',
        type: 'date',
        disEditable: true,
      },
      {
        span: 4,
        index: 'status',
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        displayValue: this.trans(SchemeStatusTextMap[this.detailData.status]),
        disEditable: true,
      },
    ]
  }

  trans(str: string, params?: Object): string {
    return this.i18n.fanyi(str, params)
  }

  currencyRequiredHandler(): void {
    this.msg.error(this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.TRANSACTION_CURRENCY') }))
  }

  triggerBaseEdit() {
    // 编辑方案  TODO
    this.riskStore.setValue(this.detailData)
    if (this.detailData.insCode) {
      this.acquirerService
        .getOne(this.detailData.insCode as string)
        .pipe(take(1))
        .subscribe(data => {
          this.detailData.insCode = {
            code: data.institution.common.insCode,
            num: data.institution.common.insCode,
            level: 'institution',
            nameEN: data.institution.common.insNameEN,
            name: data.institution.common.insName,
          }
          this.router.navigate(['postRisk/creatRiskScheme/update'], { queryParams: { type: 2 } })
        })
    } else {
      this.router.navigate(['postRisk/creatRiskScheme/update'], { queryParams: { type: 2 } })
    }
  }
}
